package com.jijuxie.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jijuxie.common.core.R;
import com.jijuxie.system.domain.SysUser;
import com.jijuxie.system.domain.dto.LoginDTO;
import com.jijuxie.system.domain.dto.PasswordDTO;
import com.jijuxie.system.service.ISysUserService;
import com.jijuxie.common.service.FileService;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import org.springframework.beans.factory.annotation.Value;

/**
 * 用户管理控制器 处理用户账号及个人信息管理
 *
 * @author jijuxie
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController {

    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private FileService fileService;
    
    @Value("${upload.path:D:/jijuxie/upload/}")
    private String uploadPath;
    
    @Value("${upload.url:/profile/}")
    private String uploadUrl;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        return R.ok(token);
    }

    /**
     * 用户注册 创建新用户账号
     *
     * @param user 用户信息
     */
    @PostMapping("/register")
    public R<Void> register(@RequestBody SysUser user) {
        userService.register(user);
        return R.ok();
    }

    /**
     * 获取用户列表 支持分页查询和多条件筛选
     *
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param user 查询条件
     */
    @GetMapping("/list")
    public R<Page<SysUser>> list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            SysUser user) {
        Page<SysUser> page = userService.page(new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<SysUser>()
                        .like(user.getUsername() != null, SysUser::getUsername, user.getUsername())
                        .like(user.getPhoneNumber() != null, SysUser::getPhoneNumber, user.getPhoneNumber())
                        .eq(user.getStatus() != null, SysUser::getStatus, user.getStatus())
                        .orderByDesc(SysUser::getCreateTime));
        return R.ok(page);
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping("/{userId}")
    public R<SysUser> getInfo(@PathVariable Long userId) {
        return R.ok(userService.selectUserById(userId));
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public R<SysUser> getCurrentUserInfo() {
        return R.ok(userService.getById(StpUtil.getLoginIdAsLong()));
    }

    /**
     * 获取当前用户个人资料
     */
    @GetMapping("/profile/info")
    public R<SysUser> getProfile() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("获取用户个人资料，用户ID: {}", userId);
        return R.ok(userService.getById(userId));
    }

    /**
     * 更新当前用户个人资料 (处理表单数据和文件上传)
     */
    @PostMapping(value = "/profile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> updateProfile(
            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
            @RequestParam(value = "nickName", required = false) String nickName,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "sex", required = false) String sex) {
        
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("更新用户个人资料(表单方式)，用户ID: {}", userId);
        
        SysUser user = userService.getById(userId);
        if (user == null) {
            return R.fail("用户不存在");
        }
        
        // 更新用户信息
        if (nickName != null) {
            user.setNickName(nickName);
        }
        if (email != null) {
            user.setEmail(email);
        }
        if (phone != null) {
            user.setPhoneNumber(phone);
        }
        if (sex != null) {
            user.setSex(sex);
        }
        
        // 处理头像上传
        if (avatar != null && !avatar.isEmpty()) {
            try {
                // 删除旧头像
                if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                    fileService.deleteFile(user.getAvatar());
                }
                
                // 上传新头像
                String avatarUrl = fileService.uploadAvatar(avatar, userId);
                user.setAvatar(avatarUrl);
                log.info("用户头像已更新，用户ID: {}, 新头像: {}", userId, avatarUrl);
            } catch (Exception e) {
                log.error("保存头像失败", e);
                return R.fail("头像上传失败：" + e.getMessage());
            }
        }
        
        userService.updateUser(user);
        log.info("用户个人资料已更新，用户ID: {}", userId);
        return R.ok();
    }
    
    /**
     * 更新当前用户个人资料 (处理JSON数据)
     */
    @PostMapping(value = "/profile", consumes = MediaType.APPLICATION_JSON_VALUE)
    public R<Void> updateProfileJson(@RequestBody Map<String, Object> profileData) {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("更新用户个人资料(JSON方式)，用户ID: {}, 数据: {}", userId, profileData);
        
        try {
            SysUser user = userService.getById(userId);
            if (user == null) {
                return R.fail("用户不存在");
            }
            
            // 更新用户信息
            if (profileData.containsKey("nickName")) {
                user.setNickName((String) profileData.get("nickName"));
            }
            if (profileData.containsKey("email")) {
                user.setEmail((String) profileData.get("email"));
            }
            if (profileData.containsKey("phone")) {
                user.setPhoneNumber((String) profileData.get("phone"));
            }
            if (profileData.containsKey("sex")) {
                user.setSex((String) profileData.get("sex"));
            }
            // 处理avatar URL (不是文件上传)
            if (profileData.containsKey("avatar") && profileData.get("avatar") != null) {
                user.setAvatar((String) profileData.get("avatar"));
            }
            
            userService.updateUser(user);
            log.info("用户个人资料已更新(JSON方式)，用户ID: {}", userId);
            return R.ok();
        } catch (Exception e) {
            log.error("更新用户资料失败", e);
            return R.fail("更新用户资料失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改用户
     */
    @PutMapping
    public R<Void> update(@RequestBody SysUser user) {
        userService.updateUser(user);
        return R.ok();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public R<Void> remove(@PathVariable Long[] userIds) {
        for (Long userId : userIds) {
            userService.removeById(userId);
        }
        return R.ok();
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody SysUser user) {
        userService.resetPassword(user.getUserId(), user.getPassword());
        return R.ok();
    }

    /**
     * 修改密码 验证旧密码后更新新密码
     *
     * @param passwordDTO 密码信息(旧密码、新密码)
     */
    @PutMapping("/password")
    public R<Void> updatePassword(@RequestBody PasswordDTO passwordDTO) {
        userService.updatePassword(StpUtil.getLoginIdAsLong(),
                passwordDTO.getOldPassword(), passwordDTO.getNewPassword());
        return R.ok();
    }
}
